package com.bdqn.controller;

import com.bdqn.entity.CommonResult;
import com.bdqn.entity.Payment;
import com.bdqn.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {
    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    //新增支付信息
    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("*****插入结果：" + result);
        if (result > 0) { //成功
            return new CommonResult(200, "插入数据库成功"+ serverPort, result);
        } else {
            return new CommonResult(444, "插入数据库失败"+ serverPort, null);
        }
    }

    //通过 ID 查询支付信息。
    @GetMapping(value = "/payment/get/{id}")
    //@ResponseBody
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        log.info("*****查询结果：" + payment);
        if (payment != null) { //说明有数据，能查询成功
            return new CommonResult(200, "查询成功"+ serverPort, payment);
        } else {
            return new CommonResult(444, "没有对应记录，查询 ID：" + id, null);
        }
    }

    /**
     * 超时设置
     * 用于模拟程序进行业务逻辑花费3秒钟，而我们服务消费者cloud-consumer-feign-order80用OpenFeign
     * 调用 8001 模块理论上默认 1 秒钟之内就要获取到响应信息，一旦超过 1 秒钟就会报错(我们下面代码会使用 OpenFeign 在调用过程中铁定报错)。
     * @return
     */
    @GetMapping(value = "/payment/feign/timeout")
    public String paymentFeignTimeout(){
        try {
            // 模拟程序进行业务逻辑花费了 3 秒钟
            TimeUnit.SECONDS.sleep(3);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}